#!/usr/bin/python3

import asyncio, evdev

# 按键转字符表 只列出了常用的字符
keymap = {
	'KEY_0': u'0',
	'KEY_1': u'1',
	'KEY_2': u'2',
	'KEY_3': u'3',
	'KEY_4': u'4',
	'KEY_5': u'5',
	'KEY_6': u'6',
	'KEY_7': u'7',
	'KEY_8': u'8',
	'KEY_9': u'9',
	'KEY_A': u'A',
	'KEY_B': u'B',
	'KEY_C': u'C',
	'KEY_D': u'D',
	'KEY_E': u'E',
	'KEY_F': u'F',
	'KEY_G': u'G',
	'KEY_H': u'H',
	'KEY_I': u'I',
	'KEY_J': u'J',
	'KEY_K': u'K',
	'KEY_L': u'L',
	'KEY_M': u'M',
	'KEY_N': u'N',
	'KEY_O': u'O',
	'KEY_P': u'P',
	'KEY_Q': u'Q',
	'KEY_R': u'R',
	'KEY_S': u'S',
	'KEY_T': u'T',
	'KEY_U': u'U',
	'KEY_V': u'V',
	'KEY_W': u'W',
	'KEY_X': u'X',
	'KEY_Y': u'Y',
	'KEY_Z': u'Z',
	'KEY_TAB': u'\t',
	'KEY_SPACE': u' ',
	'KEY_COMMA': u',',
	'KEY_SEMICOLON': u';',
	'KEY_EQUAL': u'=',
	'KEY_LEFTBRACE': u'[',
	'KEY_RIGHTBRACE': u']',
	'KEY_MINUS': u'-',
	'KEY_APOSTROPHE': u'\'',
	'KEY_GRAVE': u'`',
	'KEY_DOT': u'.',
	'KEY_SLASH': u'/',
	'KEY_BACKSLASH': u'\\',
	'KEY_ENTER': u'\n',
}

# 检测到输入时触发
async def print_events(device):
	buf = ''
	async for event in device.async_read_loop():
		# key_up= 0 key_down= 1 key_hold= 2
		if event.type == evdev.ecodes.EV_KEY and event.value == 1:
			kv = evdev.events.KeyEvent(event)
			# print(device.path, evdev.categorize(event), sep=': ')
			# print(kv.keycode, keymap.get(kv.keycode) or 'unknown')
			if (kv.scancode == evdev.ecodes.KEY_ENTER):
				print('读到输入: ', buf)
				'''
				业务逻辑
				'''
				# 清空 buffer
				buf = ''
			else:
				buf += keymap.get(kv.keycode)
			
	
# 列出 usb 设备
devices = [evdev.InputDevice(path) for path in evdev.list_devices()]

# for index in evdev.ecodes.KEY:
# 	print(index, evdev.ecodes.KEY[index])

print('发现以下设备: ')
for device in devices:
	print(device.path, device.name, device.phys)

for device in devices:
	asyncio.ensure_future(print_events(device))

loop = asyncio.get_event_loop()
loop.run_forever()
